const { Server } = require("socket.io")
const path = require('path')
const { query } = require('./querySql');
class Socket {
    io = null
    admins = new Set()
    users = new Set()
    init() {
        this.io = new Server({
            cors: {
                origin: '*'
            }
        })
        this.io.on('connection', (socket) => {
            const role = socket.handshake.query.role;
            if (role == 'admin') {
                console.log('Admin connection');
                this.admins.add(socket)
            }
            socket.on('disconnect', () => {
                if (this.admins.has(socket)) {
                    console.log('Admin disconnected');
                    this.admins.delete(socket);
                }
            });
            socket.on('send_code', async (code, cb) => {
                if(code){
                    let sql = `
                    SELECT
                        G.id AS good_id,
                        S.id AS id,
                        S.name AS code,
                        A.name AS admin_name,
                        G.name AS good_name,
                        C.name AS customer_name,
                        C.phone AS customer_phone,
                        C.time AS customer_time,
                        CG.instock_time AS instock_time,
                        CG.outstock_time AS outstock_time,
                        CG.is_out AS is_out
                    FROM
                        storehouse S
                    JOIN
                        goods G ON G.id = S.id
                    JOIN
                        admin_user A ON A.id = G.admin_id
                    JOIN
                        customer C ON C.id = G.customer_id
                    JOIN
                        storehouse_goods CG ON CG.storehouse_id = S.id
                    WHERE
                        S.name = '${code}'
                    `
                    let goodid = await query(sql)
                    if(goodid.length){
                        cb({
                            type: 'success',
                            msg: '提交成功!',
                        })
                        for(const adminSocket of this.admins){
                            adminSocket.emit('send_code', goodid[0]);
                        }
                    }else{
                        cb({
                            type: 'warning',
                            msg: '取件码无效!'
                        })
                    }
                }else{
                  cb({
                      type: 'error',
                      msg: '请输入取件码!'
                  })
                }
            });
        });
        this.io.listen(3000)
    }
}

module.exports = new Socket()
